<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="50%"
    title="新增"
    :dialog-style="{ top: '20px' }"
    :footer="null"
  >
    <div v-if="visible" v-permission="['promotions:coupon:add']" v-loading="loading">
      <a-form
        ref="form"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
        :model="formData"
        :rules="rules"
      >
        <a-divider>基本信息</a-divider>
        <a-form-item label="活动名称" name="name">
          <a-input v-model:value="formData.name" max-length="20" allow-clear />
        </a-form-item>
        <cycle-form
          ref="cycleForm"
          v-model:begin-date="formData.beginDate"
          v-model:end-date="formData.endDate"
          v-model:cycle-flag="formData.cycleFlag"
          v-model:cycle-type="formData.cycleType"
          v-model:cycle-time-group="formData.cycleTimeGroup"
          v-model:cycle-time-rule="formData.cycleTimeRule"
        />
        <a-form-item label="适用人群" name="allMemberLevel">
          <a-row>
            <a-col :span="24">
              <div style="padding-top: 5px">
                <a-radio-group
                  v-model:value="formData.allMemberLevel"
                  @change="
                    () => {
                      formData.memberLevelId = [];
                    }
                  "
                >
                  <a-radio
                    v-for="item in $enums.MEMBER_LEVEL_TYPE.values()"
                    :key="item.code"
                    :value="item.code"
                    >{{ item.desc }}</a-radio
                  >
                </a-radio-group>
              </div>
            </a-col>
          </a-row>
          <a-row v-if="formData.allMemberLevel === 3">
            <a-col :span="24">
              <div style="padding-top: 5px">
                <member-level-selector
                  v-model:value="formData.memberLevelId"
                  :multiple="true"
                  :show-sum="true"
                />
              </div>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="购买限制" name="cycleBuyLimit">
          <a-row>
            <a-col :span="24">
              <div style="padding-top: 5px">
                <a-radio-group
                  v-model:value="formData.allBuyLimit"
                  @change="
                    () => {
                      if (formData.allBuyLimit) {
                        formData.cycleBuyLimit = 1;
                      } else {
                        formData.cycleBuyLimit = 0;
                      }
                    }
                  "
                >
                  <a-radio :value="false">不限制</a-radio>
                  <a-radio :value="true">每人限购</a-radio>
                </a-radio-group>
              </div>
            </a-col>
          </a-row>
          <a-row v-if="formData.allBuyLimit">
            <a-col :span="24">
              <div style="padding-top: 5px">
                <a-input-number
                  style="width: 100%"
                  v-model:value="formData.cycleBuyLimit"
                  :min="1"
                  allow-clear
                />
              </div>
            </a-col>
          </a-row>
        </a-form-item>
        <a-divider>参与设置</a-divider>
        <a-form-item label="参与门店" name="allShop">
          <a-row>
            <a-col :span="24">
              <div style="padding-top: 5px">
                <a-radio-group v-model:value="formData.allShop">
                  <a-radio :value="true">全部门店</a-radio>
                  <a-radio :value="false">指定门店</a-radio>
                </a-radio-group>
              </div>
            </a-col>
          </a-row>
          <a-row v-if="!formData.allShop">
            <a-col :span="24">
              <shop-selector v-model:value="formData.shopId" :multiple="true" :show-sum="true" />
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="参与卡券" name="couponId">
          <coupon-selector v-model:value="formData.couponId" :multiple="true" :show-sum="true" />
        </a-form-item>
        <div class="form-modal-footer">
          <a-space>
            <a-button type="primary" :loading="loading" html-type="submit" @click="submit">
              保存
            </a-button>
            <a-button :loading="loading" @click="closeDialog">取消</a-button>
          </a-space>
        </div>
      </a-form>
    </div>
  </a-modal>
</template>
<script>
  import { defineComponent } from 'vue';
  import * as api from '@/api/promotions/coupon';
  import dayjs from 'dayjs';
  import AButton from '@/components/Button/src/BasicButton.vue';
  import CycleForm from '@/views/promotions/cycleForm.vue';
  import MemberLevelSelector from '@/components/Selector/src/MemberLevelSelector.vue';
  import ShopSelector from '@/components/Selector/src/ShopSelector.vue';
  import CouponSelector from '@/components/Selector/src/CouponSelector.vue';

  export default defineComponent({
    components: {
      CouponSelector,
      ShopSelector,
      MemberLevelSelector,
      CycleForm,
      AButton,
    },
    data() {
      return {
        // 是否可见
        visible: false,
        // 是否显示加载框
        loading: false,
        presets: [
          { label: '今天', value: [dayjs(), dayjs()] },
          { label: '最近3天', value: [dayjs(), dayjs().add(3, 'day')] },
          { label: '最近7天', value: [dayjs(), dayjs().add(7, 'day')] },
          { label: '最近30天', value: [dayjs(), dayjs().add(30, 'day')] },
        ],
        // 表单数据
        formData: {},
        // 表单校验规则
        rules: {
          name: [{ required: true, message: '请输入促销活动名称' }],
          beginDate: [{ required: true, message: '请输入促销活动开始时间' }],
          endDate: [{ required: true, message: '请输入促销活动结束时间' }],
          cycleFlag: [{ required: true, message: '请输入活动期间是否周期执行' }],
          cycleType: [{ required: true, message: '请输入周期类型(1:每天; 2:每周; 3:每月)' }],
          cycleTimeGroup: [{ required: true, message: '请输入周期执行时间段' }],
          cycleTimeRule: [{ required: true, message: '请输入周期执行规则' }],
          memberLevelId: [{ required: true, message: '请输入会员等级id' }],
          allBuyLimit: [{ required: true, message: '请输入是否限制购买数量' }],
          cycleBuyLimit: [{ required: true, message: '请输入周期限购数量' }],
          shopId: [{ required: true, message: '请输入门店id' }],
          couponId: [{ required: true, message: '请输入卡券id' }],
        },
      };
    },
    computed: {
      range_date() {
        return [
          this.formData.beginDate ? dayjs(this.formData.beginDate) : null,
          this.formData.endDate ? dayjs(this.formData.endDate) : null,
        ];
      },
    },
    created() {
      // 初始化表单数据
      this.initFormData();
    },
    methods: {
      dayjs,
      // 打开对话框 由父页面触发
      openDialog() {
        this.visible = true;

        this.$nextTick(() => this.open());
      },
      // 关闭对话框
      closeDialog() {
        this.visible = false;
        this.$emit('close');
      },
      // 初始化表单数据
      initFormData() {
        this.formData = {
          name: '',
          beginDate: '',
          endDate: '',
          cycleFlag: false,
          cycleType: 1,
          cycleTimeGroup: [
            {
              beginTime: '',
              endTime: '',
            },
          ],
          cycleTimeRule: [],
          promPrice: {},
          allMemberLevel: 1,
          memberLevelId: '',
          allBuyLimit: false,
          cycleBuyLimit: 0,
          allShop: true,
          shopId: [],
          couponId: [],
        };
      },
      // 提交表单事件
      submit() {
        let formValidPromise = this.$refs.form.validate();
        let cycleFormValidPromise = this.$refs.cycleForm.validateForm();
        Promise.allSettled([formValidPromise, cycleFormValidPromise]).then((results) => {
          if (results[0].status === 'fulfilled' && results[1].status === 'fulfilled') {
            api
              .create({
                ...this.formData,
                beginDate: this.formData.beginDate + ' 00:00:00',
                endDate: this.formData.endDate + ' 23:59:59',
                cycleTimeGroup: JSON.stringify(this.formData.cycleTimeGroup),
                cycleTimeRule: JSON.stringify(this.formData.cycleTimeRule),
                memberLevelId: JSON.stringify(this.formData.memberLevelId),
                shopId: JSON.stringify(this.formData.shopId),
                couponId: JSON.stringify(this.formData.couponId),
              })
              .then(() => {
                this.$msg.createSuccess('新增成功！');
                this.$emit('confirm');
                this.visible = false;
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },
      // 页面显示时触发
      open() {
        // 初始化表单数据
        this.initFormData();
      },
    },
  });
</script>
